<template>
  <view class="player-container">
    <uni-forms ref="playerRef" :model="playerForm" :rules="playerRules">
      <uni-forms-item name="images">
        <uni-file-picker
          limit="1"
          title="最多选择1张图片"
          fileMediatype="image"
          @select="imageSuccess"
          @delete="imagesDelete"
          v-model="playerForm.images"
        ></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item label="选手名称:" name="tittle" label-width="85">
        <uni-easyinput
          type="text"
          v-model="playerForm.tittle"
          placeholder="请输入投票标题"
        ></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item label="选手描述:" name="intro" label-width="85">
        <uni-easyinput
          type="textarea"
          v-model="playerForm.intro"
          placeholder="请输入投票内容"
        ></uni-easyinput>
      </uni-forms-item>
      <view class="form-btn-container">
        <button @click="signUpSubmit" class="submit-btn">报名</button>
      </view>
    </uni-forms>
  </view>
</template>

<script setup lang="ts">
import { reactive, ref } from "vue";
import { addPlayerType, imageType, PublishState } from "@/types/vote";
import { addPlayerAPI } from "@/api/player";
import { uploadFileAPI } from "@/api/file";

// 接收页面参数
const query = defineProps<{
  id: string;
}>();

const playerForm: addPlayerType = reactive({
  images: [],
  tittle: "",
  intro: "",
  cover: "",
  state: PublishState.pending,
  actId: query.id,
});

// 表单规则
const playerRules: UniHelper.UniFormsRules = {
  images: {
    rules: [{ required: true, errorMessage: "请上传选手图片" }],
  },
  tittle: {
    rules: [
      { required: true, errorMessage: "请输入选手名称" },
      { maxLength: 16, errorMessage: "选手名称不能超过16个字符" },
    ],
  },
  intro: {
    rules: [
      {
        required: true,
        errorMessage: "请输入选手描述",
      },
      { maxLength: 100, errorMessage: "选手描述不能超过100个字符" },
    ],
  },
};
const playerRef = ref<UniHelper.UniFormsInstance>();

//重置表单
const resetForm = () => {
  playerForm.images = [];
  playerForm.tittle = "";
  playerForm.intro = "";
  playerForm.cover = "";
};

const playerUploadFile = async (imageList: imageType[]) => {
  const uploadPromises = imageList.map((item) => uploadFileAPI(item));
  try {
    const responses = await Promise.all(uploadPromises);
    const fileUrlList = responses.flatMap((res) => res.data.fileUrl);
    playerForm.cover = fileUrlList.join(","); // 使用 join 代替 toString
  } catch (error) {
    console.error("上传文件时发生错误：", error);
    // 处理错误的逻辑，比如显示提示信息等
  }
};

const signUpSubmit = async () => {
  await playerRef.value?.validate?.();
  await playerUploadFile(playerForm.images);
  await addPlayerAPI(playerForm);
  uni.showToast({
    title: "报名成功",
    icon: "success",
    duration: 1000,
  });
  resetForm();
  setTimeout(() => {
    uni.navigateBack();
  }, 1000);
};

const imageSuccess: UniHelper.UniFilePickerOnSuccess = (event) => {
  const imageDatas = event.tempFiles.map((item: any) => {
    return { url: item.url, name: item.name };
  });
  playerForm.images.push(...imageDatas);
};

const imagesDelete: UniHelper.UniFilePickerOnDelete = (event) => {
  playerForm.images.splice(event.index, 1);
};
</script>

<style scoped lang="scss">
.player-container {
  padding: 20px;
  .form-btn-container {
    display: flex;
    justify-content: space-between;

    .submit-btn {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 500rpx;
      background-color: #2979ff;
      height: 80rpx;
      font-size: 28rpx;
      border-radius: 8rpx;
      color: #fff;
    }
  }
}
</style>
